import React, { useState, useEffect, useContext } from 'react'
import { useSelector } from 'react-redux'
import moment from 'dayjs'
import { Table, Button } from 'antd'
import { getPlanMonitor } from '&/api/electricity'
import Container from '@/appComponents/Container'
import Filter from './Filter'
import downloadExcelImg from '&/commonjs/downloadExcelImg'
import { LayoutContext } from '&/pages/layouts/context'
import './index.scss'
const defaultColumns = [
  {
    title: '序号',
    width: 70,
    render: (_, __, index) => `${index + 1}`,
    align: 'center',
    fixed: 'left'
  },
  {
    title: '企业名称',
    width: 260,
    dataIndex: 'ent_name',
    key: 'ent_name',
    align: 'center',
    fixed: 'left'
  },
  {
    title: '累计落实小时数',
    width: 100,
    dataIndex: 'count',
    key: 'count',
    align: 'center',
    fixed: 'left'
  },
  {
    title: '区',
    width: 100,
    dataIndex: 'county_name',
    key: 'county_name',
    align: 'center',
    fixed: 'left'
  },
  {
    title: '行业',
    width: 100,
    dataIndex: 'industry_name',
    key: 'industry_name',
    align: 'center',
    fixed: 'left'
  },
  {
    title: '实时状态',
    align: 'center',
    children: []
  }
]
const renderPolygon = (type) => {
  return <span className={type ? 'square' : 'triangle'} />
}

const PlanMonitoing = () => {
  const { activePlan } = useContext(LayoutContext)
  const [curretTime, setCurrentTime] = useState(moment())
  const [planData, setPlanData] = useState({})
  const [tableData, setTableData] = useState([])
  const [loading, setLoading] = useState()
  const [pageInfo, setPageInfo] = useState({})
  const [practicable, setPracticable] = useState({
    practicable: '',
    unpracticable: ''
  })
  const [columns] = useState(defaultColumns)
  const panse = useSelector((state) => state.getPanesReducer)
  const [paramsData, setParamsData] = useState({
    start_time: moment(activePlan.start_time).format('YYYY-MM-DD HH:00:00'),
    end_time: moment(activePlan.end_time).format('YYYY-MM-DD HH:00:00'),
    county_id: -1,
    industry_id: -1,
    ent_name: '',
    page: 1,
    page_size: 2000
  })
  useEffect(() => {
    setParamsData((state) => {
      state.start_time = moment(activePlan.start_time).format(
        'YYYY-MM-DD HH:00:00'
      )
      state.end_time = moment(activePlan.end_time).format('YYYY-MM-DD HH:00:00')
      onQuery()
      return {
        ...state
      }
    })
  }, [activePlan.plan_id])

  useEffect(() => {
    // 不是第一次进入，刷新列表
    if (panse.activeKey === 'PlanMonitoing' && tableData.length) {
      onReload()
      setCurrentTime(moment())
    }
  }, [panse])

  const onQuery = async (v) => {
    setLoading(true)
    let json = handlerParams(paramsData)
    let res = await getPlanMonitor({
      ...json,
      plan_id: activePlan.plan_id
    })
    setLoading(false)
    setPageInfo(res.page_info)
    setPlanData(res.plan_data)
    setPracticable({
      practicable: res.practicable,
      unpracticable: res.unpracticable
    })
    const children = res.time_data?.map((t) => {
      return {
        title: t,
        dataIndex: `${t}`,
        key: `${t}`,
        align: 'center',
        width: res.time_data?.length <= 12 ? null : 80,
        render: renderPolygon
      }
    })
    columns[5].title = '实时监控企业设备是否全部落实措施'
    columns[5].className = res.time_data.length ? 'colspan_name' : ''
    columns[5].children = children
    const keys = Object.values(res.time_data)
    const data = res.ent_data.map((ent) => {
      const {
        ent_id,
        ent_name,
        dev_num,
        status,
        count,
        county_name,
        industry_name
      } = ent
      const o = {
        ent_id,
        ent_name,
        dev_num,
        count,
        county_name,
        industry_name
      }
      status?.forEach((s, i) => {
        o[keys[i]] = s
      })
      return o
    })
    setTableData(data)
  }
  const handlerParams = (params) => {
    let newParams = {}
    for (let key in params) {
      if (params[key] !== -1) {
        newParams[key] = params[key]
      }
    }
    return newParams
  }
  const downloadExcel = () => {
    downloadExcelImg(tableData, columns, '过程监控')
  }
  return (
    <Container>
      <Container.ContainerQuery title="查询条件">
        <Filter
          handleQuery={onQuery}
          paramsData={paramsData}
          setParamsData={setParamsData}
          loading={loading}
        />
      </Container.ContainerQuery>
      <Container.ContainerContent>
        <div className="PlanMonitoing_title">
          <div className="tit">查询结果</div>
          <div className="sub">
            <div>最近1小时落实企业数：{practicable.practicable}家</div>
            <div>最近1小时未落实企业数：{practicable.unpracticable}家</div>
            {/* <Button type="primary" onClick={() => {downloadExcel()}}>
              导出
            </Button> */}
          </div>
        </div>
        <Table
          className="PlanMonitoing_table"
          bordered
          loading={loading}
          columns={columns}
          dataSource={tableData}
          pagination={{ ...pageInfo, defaultPageSize: 20 }}
          size="small"
          scroll={{
            y: '62vh'
          }}
        />
      </Container.ContainerContent>
    </Container>
  )
}
export default PlanMonitoing
